#include "moz_repl.hpp"
#include <iostream>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <boost/algorithm/string.hpp>

const char moz_repl::DELIMITER = '=';
const std::string moz_repl::PORT = "port";
const std::string moz_repl::HOST = "server";
const std::string moz_repl::APPLICATION = "application";
const char moz_repl::COMMENT = '#';

void moz_repl::init_from(std::string const& filename)
{
	if(!filename.empty())
		parse(filename.c_str());
}

void moz_repl::init_from(const char* filename)
{
	if(filename !=NULL)
		parse(filename);
}

void moz_repl::parse(const char* filename)
{
	std::string line;
	std::ifstream input_file(filename);
	if (input_file.is_open())
	{
		while ( input_file.good() )
		{
			std::getline (input_file,line);
			line = boost::trim_left_copy(line);
			if(line[0] == COMMENT) continue;

			std::string directive = line.substr(0, line.find_first_of(DELIMITER));
			boost::trim(directive);

			std::string directive_data = line.substr(line.find_first_of(DELIMITER)+1, line.length());
			boost::trim(directive_data);

			if(directive == PORT)
			{
				//std::stringstream str(directive_data);
				//str >> port_number;
				_port_param = directive_data;
			}
			else if (directive == HOST)
			{
				hostname = directive_data;
			}
			else if (directive == APPLICATION)
			{
				_application = directive_data;
			}
		}
	}

	input_file.close();
}

std::string const moz_repl::connection_str()
{
	//std::stringstream port;
	//std::string port_no;

	//port << port_number;
	//port >> port_no;

	//std::string connection_str = _application + ' ' + hostname + ' ' + port_no;
	std::string connection_str = _application + ' ' + hostname + ' ' + _port_param;
	std::cout << connection_str << std::endl;

	return connection_str;
	
}


//moz_repl::moz_repl(): port_number(4242), hostname("localhost"), _application("telnet")
moz_repl::moz_repl(): _port_param("4242"), hostname("localhost"), _application("telnet")
{}

//void moz_repl::set_port_number(unsigned int p)
void moz_repl::set_port_param(std::string const& p)
{
	_port_param=p;
}

void moz_repl::set_hostname(std::string const& s)
{
	hostname = s;
}


void moz_repl::set_application(std::string const& s)
{
	_application = s;
}
